package cn.edu.nchu.service.impl;

import cn.edu.nchu.service.MqttService;
import cn.edu.nchu.stream.MySink;
import cn.edu.nchu.stream.MySource;
import cn.edu.nchu.service.MQService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

@Service
@EnableBinding({MySource.class, MySink.class})
public class MQServiceImpl implements MQService {
    @Autowired
    private MySource mySource;
    @Autowired
    private MqttService mqttService;

    @Override
    public void doNothing(JSONObject m) {

    }

    // 发去队列
    @Override
    public void sendMessage(String topic, JSONObject message) {
        switch (topic) {
            case "messages/up" -> mySource.messages_up().send(MessageBuilder.withPayload(message).build());
            case "commands/response" -> mySource.commands_response().send(MessageBuilder.withPayload(message).build());
            case "properties/report" -> mySource.properties_report().send(MessageBuilder.withPayload(message).build());
        }
    }

    @StreamListener(value = MySink.MESSAGE_DOWN)
    public void recive_message_down(@Payload JSONObject message) {
        reciveMessage("message/down", message);
    }

    @StreamListener(value = MySink.COMMANDS_REQUEST)
    public void recive_commands_request(@Payload JSONObject message) {
        reciveMessage("commands/request", message);
    }

    // 发去mqtt
    @Override
    public void reciveMessage(String topic, JSONObject message) {
        mqttService.sendMessage(topic, message.toJSONString());
    }
}
